package de.gwtprime.client.widgets.trading.popup;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.web.bindery.requestfactory.shared.Receiver;

import de.gwtprime.client.ClientFactory;
import de.gwtprime.client.event.PaymentTriggeredEvent;
import de.gwtprime.client.util.GWTUtils;
import de.gwtprime.shared.requestFactory.OrderProxy;
import de.gwtprime.shared.requestFactory.OrderProxy.OrderState;
import de.gwtprime.shared.requestFactory.request.OrderRequest;

public class PaymentPopup extends PopupPanel {

	private static PaymentPopupUiBinder uiBinder = GWT
			.create(PaymentPopupUiBinder.class);

	interface PaymentPopupUiBinder extends UiBinder<Widget, PaymentPopup> {
	}
	
	@UiField HTML price;
	
	@UiField Label recipientName;
	@UiField Label recipientBank;
	@UiField Label recipientBIC;
	@UiField Label recipientIBAN;
	
	@UiField
	Button button;


	public PaymentPopup(final ClientFactory clientFactory, final OrderProxy order) {
		super(true, true); // auto hide and modal
		setWidget(uiBinder.createAndBindUi(this));
		
		
		price.setHTML(GWTUtils.I18n.paymentInstructions(order.getAmount() * order.getPrice()*(100-order.getFee()/2)/100));
		
	//	price.setText(String.valueOf(order.getAmount() * order.getPrice()));
		
		button.setText("Zahlung angewiesen");
		
		recipientName.setText(order.getSeller().getBankRecipient());
		recipientBIC.setText(order.getSeller().getBankBIC());
		recipientIBAN.setText(order.getSeller().getBankIBAN());
		//recipientName.setText(order.getSeller().getBank());
		
		
		
		if(order.getState()!=OrderState.WAITING_FOR_PAYMENT){
			button.setEnabled(false);
		}
		
		button.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				
				button.setEnabled(false);

				OrderRequest request = clientFactory.getRequestFactory().orderRequest();
				
				OrderProxy editableOrder = request.edit(order);
				
				
				
				request.paymentTriggered().using(editableOrder).fire(new Receiver<Void>(){

					@Override
					public void onSuccess(Void response) {

						clientFactory.getNotificationCenter().showMessage("Zahlung angewiesen");
						
						clientFactory.getEventBus().fireEvent(new PaymentTriggeredEvent(order));
					}
					
				});
				
			}
		});
	
	}
}
